package cloud.dandanit.itservice.service.impl;

import cloud.dandanit.itservice.entity.Rate;
import cloud.dandanit.itservice.mapper.RateMapper;
import cloud.dandanit.itservice.service.RateService;
import cloud.dandanit.itservice.utils.GenerateRandomStr;
import cloud.dandanit.itservice.utils.message.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author luokai
 * @since 2022-07-02
 */
@SuppressWarnings("AlibabaRemoveCommentedCode")
@Service
public class RateServiceImpl extends ServiceImpl<RateMapper, Rate> implements RateService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 提交评分到redis中
     * @param rate 评分
     */
    @Override
    public void submitRateToRedis(String rate) {

        redisTemplate.opsForValue().set("rate"+ RandomUtil.getSixBitRandom(), rate,2, TimeUnit.MINUTES);
    }

    /**
     * 提交评分从redis到mysql中
     */
    @Override
    public void submitRateFromRedisToMysql() {

        Set<String> rateKeys = redisTemplate.keys("rate" + "*");
        List<Rate> rateList = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(rateKeys)) {

            for (String rateKey : rateKeys) {

                Rate rate = new Rate();
                String rateNum = redisTemplate.opsForValue().get(rateKey);
                //rate.setId(GenerateRandomStr.getGenerateRandomStr19());
                rate.setRate(rateNum);
                rateList.add(rate);
            }
            redisTemplate.delete(rateKeys);
        }
        this.saveBatch(rateList);
    }
}
